/*************************************************
 * 
 * Copyright by Bruno Eberhard
 * 
 * Created on 05.08.2006
 *
 *************************************************/
package fightplan.business.util;

public class WeightUtil {

	public static final int MIN_WEIGHT = 0;
	public static final int MAX_WEIGHT = 999;
	public static final String ALL_WEIGHT = "Alle";
	public static final String FORMAT_WARNING = "Das Gewicht muss im Format \"50\" oder \"50kg\" angegeben werden.";

	public static int parse(String s) throws IllegalArgumentException {
		if (s == null)
			throw new IllegalStateException();
		s = s.trim();
		if (s.length() == 0 || "-".equals(s))
			return 0; // unbekanntes Gewicht
		int pos = s.indexOf("k", 1);
		if (pos != -1) {
			s = s.substring(0, pos).trim();
		}
		int weight = Integer.parseInt(s);
		if (weight < 0 || weight > 999)
			throw new IllegalArgumentException("Ungültiges Gewicht.");
		return weight;
	}

	public static String format(int weight) {
		if (weight > 0) {
			return weight + "kg";
		} else {
			return "";
		}
	}

	public static int parseRangeStart(String s) {
		if (s == null)
			throw new IllegalStateException();
		s = s.trim();
		if (ALL_WEIGHT.equals(s))
			return MIN_WEIGHT;
		int pos = s.indexOf("-");
		if (pos == 0)
			return MIN_WEIGHT;
		if (pos == -1)
			return parse(s);
		return parse(s.substring(0, pos));
	}

	public static int parseRangeEnd(String s) {
		if (s == null)
			throw new IllegalStateException();
		s = s.trim();
		if (ALL_WEIGHT.equals(s))
			return MAX_WEIGHT;
		int pos = s.indexOf("-");
		if (pos == s.length() - 1)
			return MAX_WEIGHT;
		if (pos == 0)
			return parse(s.substring(1));
		return parse(s.substring(pos + 1, s.length()));
	}

	public static String formatRange(int start, int end) {
		if (start <= MIN_WEIGHT) {
			if (end >= MAX_WEIGHT) {
				return "Alle";
			} else {
				return "- " + format(end);
			}
		} else {
			if (end >= MAX_WEIGHT) {
				return format(start) + " -";
			} else if (start == end) {
				return "" + format(start);
			} else {
				return format(start) + " - " + format(end);
			}
		}
	}

	public static String formatRangeForDescription(int start, int end) {
		if (start <= MIN_WEIGHT) {
			if (end >= MAX_WEIGHT) {
				return "Alle";
			} else {
				return "bis " + end + "kg";
			}
		} else {
			if (end >= MAX_WEIGHT) {
				return "ab " + start + "kg";
			} else if (start == end) {
				return start + "kg";
			} else {
				return start + "-" + end + "kg";
			}
		}
	}

}
